var express = require('express');
var Util = require('../core/Util');
var router = express.Router();
var log4js = require('log4js');
var Logger = log4js.getLogger();
var Config = require('../Config');
var SqlQuery = require('../core/SqlQuery');
var fs = require('fs');

async function validUser(req, res, isJson = false, isRequireAdmin = false) {
    var userID = Util.jwtDecode(req.cookies.ks || req.query.userToken);
    //如果不存在
    if (!userID) {
        if (!isJson)
            res.redirect('/login');
        else
            res.json({ code: 1, msg: '登录已失效，请退出重新登录' });
        return null;
    }
    var result = await SqlQuery('SELECT * FROM user WHERE userID=?',
        [userID], () => {
            res.end();
        });
    if (result.length == 0) {
        if (!isJson)
            res.redirect('/login');
        else
            res.json({ code: 1, msg: '登录已失效，请退出重新登录' });
        return null;
    }
    var user = result[0];
    if (isRequireAdmin && !user.isAdmin) {
        if (!isJson)
            res.status(404).res.render('404');
        else
            res.json({ code: 1, msg: '无权限' });
        return null;
    }
    return user;
};

router.get('/', async function (req, res, next) {
    var user = await validUser(req, res);
    if (!user)
        return;
    if (user.isAdmin)
        res.render('index', user);
    else
        res.redirect('/show');
});

router.get('/home', function (req, res, next) {
    res.render('home');
});

//退出
router.get('/logout', function (req, res, next) {
    res.cookie('ks', "", { maxAge: -1 })
    return res.redirect('/login');
});
//////////////////////////////////////////////////////////////////////////////////
router.get('/userPassEdit', async function (req, res, next) {
    if (!validUser(req, res))
        return;
    res.render('userPassEdit');
});
router.post('/userPassEdit', async function (req, res, next) {
    if (!validUser(req, res, true))
        return;

    var userPass1 = req.body.userPass1;
    var userPass2 = req.body.userPass2;
    userPass1 = Util.md5(userPass1);
    userPass2 = Util.md5(userPass2);

    if (user.userPass != userPass1)
        return res.json({ code: 2, msg: '原密码错误' });
    //更新密码
    await SqlQuery('UPDATE user SET userPass=? WHERE userID=?', [userPass2, userID], () => {
        res.json({ code: 1, msg: '数据异常' });
    });
    user.userPass = userPass2;
    res.json({
        code: 0,
        msg: '修改成功！'
    });
});
//登录页面
router.get('/login', function (req, res, next) {
    res.render('login');
});
//登录逻辑
router.post('/login', async function (req, res, next) {
    var userName = req.body.userName;
    var userPass = req.body.userPass;
    userPass = Util.md5(userPass);
    var result = await SqlQuery('SELECT * FROM user WHERE userName=? AND userPass=?',
        [userName, userPass], () => {
            res.end();
        });

    if (result.length == 0)
        return res.json({ code: 2, msg: '账号或密码错误' });
    res.cookie('ks', Util.jwtEncode(result[0].userID), { maxAge: 2147483647 })
    return res.json({ code: 0 });
});
//用户管理页面
router.get('/userManage', async function (req, res, next) {
    var user = await validUser(req, res, false, true);
    if (!user)
        return;
    res.render('userManage');
});
//获取用户列表
router.get('/userList', async function (req, res, next) {
    var user = await validUser(req, res, true, true);
    if (!user)
        return res.end();

    var page = req.query.page
    var size = req.query.limit;
    var userName = req.query.userName;
    //如果没有设置页码
    if (!page)
        page = 1;
    if (!size)
        size = 10;
    var where = ' WHERE 1';
    if (userName)
        where += ` AND userName LIKE '%${userName}%'`;
    //排序
    var field = req.query.field;
    var order = req.query.order;
    //如果存在排序关键词
    if (field) {
        if (!order)
            order = '';
        else
            order = ` ORDER BY ${field} ${order}`;
    }
    else
        order = '';

    //开始查询
    var sql = `SELECT count(*) AS count FROM user ${where};SELECT userID,userName,isAdmin FROM user ${where}${order} limit ${(page - 1) * size
        },${size}`;

    var result = await SqlQuery(sql, () => {
        res.end();
    });
    res.json({
        code: 0, count: result[0][0].count, data: result[1]
    });
});
//用户修改
router.get('/userEdit', async function (req, res, next) {
    var user = await validUser(req, res, false, true);
    if (!user)
        return res.end();

    res.render('userEdit', user);
});
//用户修改
router.post('/userEdit', async function (req, res, next) {
    var user = await validUser(req, res, true, true);
    if (!user)
        return res.end();

    var userID = req.query.userID;
    var userPass = req.body.userPass;
    userPass = Util.md5(userPass);

    await SqlQuery('UPDATE user SET userPass=? WHERE userID=?', [userPass, userID], () => { res.end(); });

    return res.json({ code: 0 });
});
//用户管理页面
router.get('/cardManage', async function (req, res, next) {
    var user = await validUser(req, res, false, true);
    if (!user)
        return;
    res.render('cardManage');
});
//获取用户列表
router.get('/show', async function (req, res, next) {
    var user = await validUser(req, res, true, false);
    if (!user)
        return res.end();

    res.render('show');
});
module.exports = router;